import { Button, message, Modal, Image } from 'antd';
import axios from 'axios';
import { useState } from 'react';

import commonService from '@/api/services/commonService';
import userStore from '@/store/userStore';

let timer: any = null;

export function ChargeModal({ show, memberRechargeId, onClose, onOk }: any) {
  const [showPay, setShowPay] = useState(false);
  const [payUrl, setPayUrl] = useState('');

  const doWeixin = () => {
    commonService.getCustomApi('/member/recharge/wxpay', { memberRechargeId }).then((res) => {
      setPayUrl(res);
      setShowPay(true);
      timer = setInterval(() => {
        checkStatus();
      }, 3000);
    });
  };

  const doAlipay = () => {
    const token = userStore.getState().userToken;
    axios({
      baseURL: import.meta.env.VITE_APP_BASE_API,
      timeout: 50000,
      method: 'get',
      url: `/member/recharge/alipay?memberRechargeId=${memberRechargeId}`,
      headers: {
        'Content-Type': 'application/json;charset=utf-8',
        Authorization: `Bearer ${token.accessToken}`,
      },
    }).then((res: any) => {
      if (res.data) {
        const newWindow: any = window.open('', '_blank');
        newWindow.document.write(res.data);
        newWindow.document.close();
        timer = setInterval(() => {
          checkStatus();
        }, 3000);
      } else {
        message.error('操作失败');
      }
    });
    // commonService.getCustomApi('/member/pay/alipay', { orderNumber }).then((res) => {
    //   console.log(res);
    // });
  };

  const closePay = () => {
    setShowPay(false);
    timer && clearInterval(timer);
  };

  const checkStatus = () => {
    commonService
      .getCustomApi('/member/recharge/listen', { id: memberRechargeId }, { noError: true })
      .then(() => {
        message.success('充值成功!');
        setShowPay(false);
        onOk();
      });
  };
  return (
    <>
      <Modal title="支付列表" open={show} onCancel={onClose} centered>
        <div className="flex gap-[20px]">
          <Button onClick={doWeixin}>微信充值</Button>
          <Button onClick={doAlipay}>支付宝</Button>
        </div>
      </Modal>
      <Modal
        title="扫码充值"
        destroyOnClose
        open={showPay}
        onCancel={closePay}
        onOk={closePay}
        centered
      >
        <div className="flex items-center justify-center">
          <Image src={`data:image/jpg;base64,${payUrl}`} preview={false} />
        </div>
      </Modal>
    </>
  );
}
